package com.ruoyi.feike.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExcelExportUtil;
import com.ruoyi.common.utils.file.AsposeUtil;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.ExcelExp;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.*;
import com.spire.doc.documents.BookmarksNavigator;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
//import java.util.HashMap;
//import java.util.Map;
import com.spire.doc.Document;

import com.spire.doc.FileFormat;

import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
import org.w3c.dom.Node;
import springfox.documentation.service.ApiListing;
//import java.io.FileOutputStream;
//import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/fileWork")
//TODO: 作为产品标准功能, 迁移到web-api-service
public class PdfController {
    @Autowired
    private IBasicInformationService basicInformationService;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private IDealercodeCountService dealercodeCountService;
    @Autowired
    private DealercodeContractMapper dealercodeContractMapper;
    @Autowired
    private DealercodeContractFilingMapper dealercodeContractFilingMapper;
    @Autowired
    private WordLabelController wordLabelController;
    @Autowired
    private IParkingLocationRegistrationService parkingLocationRegistrationService;
    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;
    @Autowired
    private ICreditConditionService creditConditionService;
    @Autowired
    private IWholesalePerformanceCurrentlyService wholesalePerformanceCurrentlyService;
    @Autowired
    private CbFleetDetailsMapper cbFleetDetailsMapper;
    @Autowired
    private ContractRecordMapper contractRecordMapper;

    @Autowired
    private HChangeLegalPersonMapper changeLegalPersonMapper;

    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private SecuritiesMapper securitiesMapper;

    @Autowired
    private ProposalByCommericalAndMarketingMapper proposalByCommericalAndMarketingMapper;

   // @Autowired
   // private OpenOfficeUtil openOfficeUtil;

    @PostMapping("/toPdf")
    public void generatePdf(@RequestBody Map parameters) {
        String contractName = (String) parameters.get("contractname");
        String instanceid = (String) parameters.get("instanceid");
        String docPath = RuoYiConfig.getProfile()+"/wordfill/word/"+instanceid+"/"+contractName+".docx";
        File file2 = new File(RuoYiConfig.getProfile()+"/wordfill/pdf/"+instanceid);
        if (file2.mkdir()) {
            System.out.println("单文件夹"+instanceid+"创建成功！创建后的文件目录为：" + file2.getPath() + ",上级文件为:" + file2.getParent());
        }
        String pdfPath = RuoYiConfig.getProfile()+"/wordfill/pdf/"+instanceid+"/"+contractName+".pdf";

//        String a = RuoYiConfig.getProfile() + parameters.get("contractlocation").toString().substring(8);
        AsposeUtil.doc2pdf(docPath,pdfPath);
//        openOfficeUtil.office2Pdf(new File(docPath), new File(pdfPath));
//        File inputWord = new File(docPath);
//        File outputFile = new File(pdfPath);
//        try  {
//            InputStream docxInputStream = new FileInputStream(inputWord);
//            OutputStream outputStream = new FileOutputStream(outputFile);
//            IConverter converter = LocalConverter.builder().build();
//            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
//            outputStream.close();
//            System.out.println("success");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    //多个word文档合并成一个
    @PostMapping("/mergeWord")
        public Map<String, Object> mergeWord(Map<String, Object> hashmap){
//            //获取第一个文档的路径
//            String filePath1 = "D:\\三方.docx";
//            //获取第二个文档的路径
//            String filePath2 = "D:\\111.docx";
//            //加载第一个文档
//            Document document = new Document(filePath1);
//            //使用insertTextFromFile方法将第二个文档的内容插入到第一个文档
//            document.insertTextFromFile(filePath2, FileFormat.Docx_2013);
//            //保存文档
//            document.saveToFile("Output.docx", FileFormat.Docx_2013);
//
//        for (int i = 0; i <map.size() ; i++) {
//            String s = map.get(i);
//        }
        String uuidid = (String)hashmap.get("instanceId");
        List<File> files = new ArrayList();
        File file = new File(RuoYiConfig.getProfile()+"/wordfill/pdf/"+uuidid);
        File[] tempList = file.listFiles();

        Arrays.sort(tempList, new Comparator<File>() {
            public int compare(File f1, File f2) {
                long diff = f1.lastModified() - f2.lastModified();
                if (diff > 0)
                    return 1;
                else if (diff == 0)
                    return 0;
                else
                    return -1;//如果 if 中修改为 返回-1 同时此处修改为返回 1  排序就会是递减
            }

            public boolean equals(Object obj) {
                return true;
            }

        });

        for (int i = 0; i < tempList.length; i++) {
            System.out.println(tempList[i].getName());
        }





        //获取该文件夹下的文件（文件都是PDF）
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i]);
            }
        }
        String a = RuoYiConfig.getProfile()+"/wordfill/pdf/Wholesale Checklist.pdf";
        List<File> collect = files.stream().filter(demo -> demo.getPath().replaceAll("\\\\","/").equals(RuoYiConfig.getProfile()+"/wordfill/pdf/"+uuidid+"/Wholesale Checklist.pdf")).collect(Collectors.toList());
        files.removeIf(demo->demo.getPath().replaceAll("\\\\","/").equals(RuoYiConfig.getProfile()+"/wordfill/pdf/"+uuidid+"/Wholesale Checklist.pdf"));
        files.add(0,collect.get(0));

        System.out.println("123");
        for (File file1 : files) {
            System.out.println(file1.getPath());
        }
        String dealerName = (String)hashmap.get("dealerName");
        String sector = (String)hashmap.get("sector");
        String limitType = (String)hashmap.get("limitType");
        boolean isPart = (Boolean) hashmap.get("isPart");
        if(isPart){
            limitType = "NormalPart";
        }
        String uuid = dealerName+sector+limitType;
        String uuidHistory = sector+limitType+dealerName;
        //拼接后的pdf存放地址
        String dizhi = RuoYiConfig.getProfile()+"/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+uuidid+"/"+uuid+".pdf";
        HashMap<String, Object> map = new HashMap<>();
        map.put("contractLocation",dizhi);
        map.put("contractName",uuid);
        map.put("contractNameHistory",uuidHistory);
        try {
            File file2 = new File(RuoYiConfig.getProfile()+"/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+uuidid);
            if (file2.mkdirs()) {
                System.out.println("多文件夹"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+"创建成功！创建后的文件目录为：" + file2.getPath() + ",上级文件为:" + file2.getParent());
            }
            File f = AsposeUtil.MulFileToOne(files, dizhi);
            System.out.println(f.length());
        } catch (Exception e){
            e.printStackTrace();
            throw new BaseException("合并pdf出错！！");
        }
        return map;
    }

    @PostMapping("/wodrpdf")
    public void testpdf(@RequestBody Map<String, Object> map){
        String instanceId = (String) map.get("instanceId");
        DealercodeContract dealercodeContract = new DealercodeContract();
        dealercodeContract.setInstanceId(instanceId);
        List<DealercodeContract> dealercodeContractsTemp = dealercodeContractMapper.dealercodeContractListgroupbypdf1(dealercodeContract);
        List<DealercodeContract> dealercodeContractsTempByDemo = dealercodeContractMapper.dealercodeContractListgroupbypdf3(dealercodeContract);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        HashMap<String, String> stringStringHashMapByDemo = new HashMap<>();
        if(dealercodeContractsTemp !=null && dealercodeContractsTemp.size()>0) {
            Map<String, List<DealercodeContract>> collect1 = dealercodeContractsTemp.stream().collect(Collectors.groupingBy(DealercodeContract::getDealerNameCN));
            for (String key : collect1.keySet()) {
                HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                hChangeLegalPerson.setDealerName(key);
                hChangeLegalPerson.setIsSuccess(0);
                List<HChangeLegalPerson> hChangeLegalPeople = changeLegalPersonMapper.selectHChangeLegalPersonList(hChangeLegalPerson);
                if (hChangeLegalPeople != null && hChangeLegalPeople.size() > 0) {
                    stringStringHashMap.put(key, "true");
                }
            }
        }
        if(dealercodeContractsTempByDemo !=null && dealercodeContractsTempByDemo.size()>0) {
            Map<String, List<DealercodeContract>> collect1 = dealercodeContractsTempByDemo.stream().collect(Collectors.groupingBy(DealercodeContract::getDealerNameCN));
            for (String key : collect1.keySet()) {
                HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                hChangeLegalPerson.setDealerName(key);
                hChangeLegalPerson.setIsSuccess(0);
                List<HChangeLegalPerson> hChangeLegalPeople = changeLegalPersonMapper.selectHChangeLegalPersonList(hChangeLegalPerson);
                if (hChangeLegalPeople != null && hChangeLegalPeople.size() > 0) {
                    stringStringHashMapByDemo.put(key, "true");
                }
            }
        }
        if(dealercodeContractsTemp !=null && dealercodeContractsTemp.size()>0){
            for (DealercodeContract contract : dealercodeContractsTemp) {
                //判断有没有出过
                boolean fjfive =false;
                DealercodeContract dealercodeContract3 = new DealercodeContract();
                dealercodeContract3.setDealerNameCN(contract.getDealerNameCN());
                dealercodeContract3.setSector(contract.getSector());
                dealercodeContract3.setLimitType(contract.getLimitType());
                dealercodeContract3.setInstanceId(instanceId);
                List<DealercodeContract> dealercodeContracts3 = dealercodeContractMapper.selectDealercodeContractListnotnull(dealercodeContract3);
                for (DealercodeContract contracts : dealercodeContracts3) {
                    if(contracts.getContractName().equals("人民币循环贷款合同附件五") || contracts.getContractName().equals("人民币循环贷款合同")){
                        fjfive = true;
                        HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                        changeLegalPerson.setDealerName(contract.getDealerNameCN());
                        changeLegalPerson.setIsSuccess(0);
                        List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                        if(changeLegalPersonS !=null && changeLegalPersonS.size()>0){
                            for (HChangeLegalPerson person : changeLegalPersonS) {
                                person.setUpdateTime(new Date());
                                person.setCandidateNo(instanceId);
                                person.setIsSuccess(1);
                                changeLegalPersonMapper.updateHChangeLegalPerson(person);
                            }
                        }
                        break;
                    }
                }
                if(stringStringHashMap.get(contract.getDealerNameCN())!=null && !fjfive){
                    HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                    changeLegalPerson.setDealerName(contract.getDealerNameCN());
                    changeLegalPerson.setIsSuccess(0);
                    List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                    if(changeLegalPersonS !=null && changeLegalPersonS.size()>0){
                        for (HChangeLegalPerson person : changeLegalPersonS) {
                            person.setUpdateTime(new Date());
                            person.setCandidateNo(instanceId);
                            person.setIsSuccess(1);
                            changeLegalPersonMapper.updateHChangeLegalPerson(person);
                            //反推修改经销商历史法人
                            BasicInformation basicInformation = new BasicInformation();
                            basicInformation.setInstanceId(instanceId);
                            basicInformation.setDealerNameCN(person.getDealerName());
                            List<BasicInformation> basicInformations = basicInformationMapper.selectBasicInformationList(basicInformation);
                            for (BasicInformation information : basicInformations) {
                                information.setOutLegalRepresentativeCN(person.getLegalRepresentativeCN());
                                basicInformationMapper.updateBasicInformation(information);
                            }

                        }
                    }
                    //新增合同
                    DealercodeContract dealercodeContractAdd = new DealercodeContract();
                    dealercodeContractAdd.setDealerNameCN(contract.getDealerNameCN());
                    dealercodeContractAdd.setSector(contract.getSector());
                    dealercodeContractAdd.setInstanceId(instanceId);
                    dealercodeContractAdd.setContract(null);
                    dealercodeContractAdd.setContractName("人民币循环贷款合同附件五");
                    dealercodeContractAdd.setContractLocation("/profile/template/人民币循环贷款合同附件五.docx");
                    dealercodeContractAdd.setLimitType(contract.getLimitType());
                    dealercodeContractAdd.setPriority(contract.getPriority());
                    DealercodeContract dealercodeContract2 = new DealercodeContract();
                    dealercodeContract2.setDealerNameCN(contract.getDealerNameCN());
                    dealercodeContract2.setSector(contract.getSector());
                    dealercodeContract2.setLimitType(contract.getLimitType());
                    dealercodeContract2.setInstanceId(instanceId);
                    List<DealercodeContract> dealercodeContracts = dealercodeContractMapper.dealercodeContractListgroupbypdf2(dealercodeContract2);
                    for (DealercodeContract dealercodeContract1 : dealercodeContracts) {
                        if(!StringUtils.isEmpty(dealercodeContract1.getContract())){
                            String[] split = dealercodeContract1.getContract().split("-");
                            dealercodeContractAdd.setContract(split[0]+"-5-1");
                            break;
                        }
                    }
                    int i = dealercodeContractMapper.insertDealercodeContract(dealercodeContractAdd);
                    //新增报表
                    ContractRecord contractRecord = new ContractRecord();
                    contractRecord.setInstanceid(instanceId);
                    contractRecord.setDealername(contract.getDealerNameCN());
                    contractRecord.setSector(contract.getSector());
                    contractRecord.setLimitType(contract.getLimitType());
                    List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(contractRecord);
                    if(contractRecords !=null && contractRecords.size()>0){
                        ContractRecord contractRecordInfo = contractRecords.get(0);
                        ContractRecord contractRecordCopy = new ContractRecord();
                        BeanUtils.copyProperties(contractRecordInfo,contractRecordCopy);
                        contractRecordCopy.setContracttype("人民币循环贷款合同附件五");
                        contractRecordCopy.setContractno(dealercodeContractAdd.getContract());
                        contractRecordMapper.insertContractRecord(contractRecordCopy);
                        contractRecordMapper.insertContractRecordThree(contractRecordCopy);

                    }

                }
            }
        }

        if(dealercodeContractsTempByDemo !=null && dealercodeContractsTempByDemo.size()>0){
            for (DealercodeContract contract : dealercodeContractsTempByDemo) {
                //判断有没有出过
                boolean fjThree =false;
                DealercodeContract dealercodeContract3 = new DealercodeContract();
                dealercodeContract3.setDealerNameCN(contract.getDealerNameCN());
                dealercodeContract3.setSector(contract.getSector());
                dealercodeContract3.setLimitType(contract.getLimitType());
                dealercodeContract3.setInstanceId(instanceId);
                List<DealercodeContract> dealercodeContracts3 = dealercodeContractMapper.selectDealercodeContractListnotnull(dealercodeContract3);
                for (DealercodeContract contracts : dealercodeContracts3) {
                    if(contracts.getContractName().equals("试乘试驾车贷款合同附件三") || contracts.getContractName().equals("试乘试驾车贷款合同")){
                        fjThree = true;
                        HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                        changeLegalPerson.setDealerName(contract.getDealerNameCN());
                        changeLegalPerson.setIsSuccess(0);
                        List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                        if(changeLegalPersonS !=null && changeLegalPersonS.size()>0){
                            for (HChangeLegalPerson person : changeLegalPersonS) {
                                person.setUpdateTime(new Date());
                                person.setCandidateNo(instanceId);
                                person.setIsSuccess(1);
                                changeLegalPersonMapper.updateHChangeLegalPerson(person);
                            }
                        }
                        break;
                    }
                }
                if(stringStringHashMapByDemo.get(contract.getDealerNameCN())!=null && !fjThree){
                    HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                    changeLegalPerson.setDealerName(contract.getDealerNameCN());
                    changeLegalPerson.setIsSuccess(0);
                    List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                    if(changeLegalPersonS !=null && changeLegalPersonS.size()>0){
                        for (HChangeLegalPerson person : changeLegalPersonS) {
                            person.setUpdateTime(new Date());
                            person.setCandidateNo(instanceId);
                            person.setIsSuccess(1);
                            changeLegalPersonMapper.updateHChangeLegalPerson(person);
                            //反推修改经销商历史法人
                            BasicInformation basicInformation = new BasicInformation();
                            basicInformation.setInstanceId(instanceId);
                            basicInformation.setDealerNameCN(person.getDealerName());
                            List<BasicInformation> basicInformations = basicInformationMapper.selectBasicInformationList(basicInformation);
                            for (BasicInformation information : basicInformations) {
                                information.setOutLegalRepresentativeCN(person.getLegalRepresentativeCN());
                                basicInformationMapper.updateBasicInformation(information);
                            }

                        }
                    }
                    //新增合同
                    DealercodeContract dealercodeContractAdd = new DealercodeContract();
                    dealercodeContractAdd.setDealerNameCN(contract.getDealerNameCN());
                    dealercodeContractAdd.setSector(contract.getSector());
                    dealercodeContractAdd.setInstanceId(instanceId);
                    dealercodeContractAdd.setContract(null);
                    dealercodeContractAdd.setContractName("试乘试驾车贷款合同附件三");
                    if(contract.getSector().toUpperCase().equals("ALFA ROMEO")){
                        dealercodeContractAdd.setContractLocation("/profile/template/Alfa Romeo/试乘试驾车贷款合同附件三.docx");
                    }
                    if(contract.getSector().toUpperCase().equals("DS")){
                        dealercodeContractAdd.setContractLocation("/profile/template/DS/试乘试驾车贷款合同附件三.docx");
                    }
                    if(contract.getSector().toUpperCase().equals("CHRYSLER")){
                        dealercodeContractAdd.setContractLocation("/profile/template/Chrysler/试乘试驾车贷款合同附件三.docx");
                    }
                    dealercodeContractAdd.setLimitType(contract.getLimitType());
                    dealercodeContractAdd.setPriority(contract.getPriority());
                    DealercodeContract dealercodeContract2 = new DealercodeContract();
                    dealercodeContract2.setDealerNameCN(contract.getDealerNameCN());
                    dealercodeContract2.setSector(contract.getSector());
                    dealercodeContract2.setLimitType(contract.getLimitType());
                    dealercodeContract2.setInstanceId(instanceId);
                    List<DealercodeContract> dealercodeContracts = dealercodeContractMapper.dealercodeContractListgroupbypdf2(dealercodeContract2);
                    for (DealercodeContract dealercodeContract1 : dealercodeContracts) {
                        if(!StringUtils.isEmpty(dealercodeContract1.getContract())){
                            String[] split = dealercodeContract1.getContract().split("-");
                            dealercodeContractAdd.setContract(split[0]+"-3-1");
                            break;
                        }
                    }
                    int i = dealercodeContractMapper.insertDealercodeContract(dealercodeContractAdd);
                    //新增报表
                    ContractRecord contractRecord = new ContractRecord();
                    contractRecord.setInstanceid(instanceId);
                    contractRecord.setDealername(contract.getDealerNameCN());
                    contractRecord.setSector(contract.getSector());
                    contractRecord.setLimitType(contract.getLimitType());
                    List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(contractRecord);
                    if(contractRecords !=null && contractRecords.size()>0){
                        ContractRecord contractRecordInfo = contractRecords.get(0);
                        ContractRecord contractRecordCopy = new ContractRecord();
                        BeanUtils.copyProperties(contractRecordInfo,contractRecordCopy);
                        contractRecordCopy.setContracttype("试乘试驾车贷款合同附件三");
                        contractRecordCopy.setContractno(dealercodeContractAdd.getContract());
                        contractRecordMapper.insertContractRecord(contractRecordCopy);
                        contractRecordMapper.insertContractRecordThree(contractRecordCopy);

                    }

                }
            }
        }
        List<DealercodeContract> dealercodeContracts = dealercodeContractMapper.dealercodeContractListgroupbypdf(dealercodeContract);

        for(DealercodeContract dc : dealercodeContracts){
            //word表头需要填充的数据
            Map<String, Object> hashMap = new HashMap<>();
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder stringBuilder1 = new StringBuilder();
            DealercodeContract dealercodeContract1 = new DealercodeContract();
            dealercodeContract1.setDealerNameCN(dc.getDealerNameCN());
            dealercodeContract1.setSector(dc.getSector());
            dealercodeContract1.setLimitType(dc.getLimitType());
            dealercodeContract1.setInstanceId(instanceId);
            //得到分类后每一组的信息
            List<DealercodeContract> dealercodeContracts1 = dealercodeContractMapper.selectDealercodeContractListnotnull(dealercodeContract1);
            //TODO 多个pdf文件里需要加一个主文件，有主合同号，对应得合同等，放在拼成的pdf第一页 合同未确定
            //然后调用合同填充方法，将这些信息全部生成在文件夹里
             //这里需要排序
            for(DealercodeContract dealercc : dealercodeContracts1){
                System.out.println("合同名称："+dealercc.getContractName());
                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("contractlocation",dealercc.getContractLocation());
                objectObjectHashMap.put("contractname",dealercc.getContractName());
                objectObjectHashMap.put("contract",dealercc.getContract());
                //部分合同包含了该分组合同的其他合同号，所以需要查对应分组的其他合同号然后标签替换
                objectObjectHashMap.put("dealername",dealercc.getDealerNameCN());
                objectObjectHashMap.put("sector",dealercc.getSector());
                objectObjectHashMap.put("limittype",dealercc.getLimitType());
                objectObjectHashMap.put("instanceid",instanceId);
                objectObjectHashMap.put("priority",dealercc.getPriority());
                wordLabelController.generateWor(objectObjectHashMap);
//                HashMap<String, Object> objectObjectHashMap1 = new HashMap<>();
//                objectObjectHashMap1.put("contractName",dealercc.getContractName());
                this.generatePdf(objectObjectHashMap);
//                if(!StringUtils.isEmpty(dealercc.getContract())){
                if(StringUtils.isEmpty(dealercc.getContract())){
                    stringBuilder.append(dealercc.getContractName()+"、");
                }else {
                    stringBuilder.append(dealercc.getContractName()+"("+dealercc.getContract()+")"+"、");
                }

//                }
                stringBuilder1.append(dealercc.getContractName()).append("\n");
            }

            String agtno = (stringBuilder.substring(0, stringBuilder.length() - 1)).toString();
            String contracts = (stringBuilder1.substring(0, stringBuilder1.length() - 1)).toString();
            hashMap.put("dealerName",dc.getDealerNameCN());
            hashMap.put("sector",dc.getSector());
            hashMap.put("limitType",dc.getLimitType());
            hashMap.put("agtNo",agtno);
            hashMap.put("contracts",contracts);
            hashMap.put("instanceId",instanceId);
            boolean isPart = false;
            if(dc.getSector().toUpperCase().equals("PEUGEOT") && (dc.getLimitType().toUpperCase().equals("NORMAL") || dc.getLimitType().toUpperCase().equals("PART"))){
                //查询
                ProposalByCommericalAndMarketing proposalByCommericalAndMarketingParts = new ProposalByCommericalAndMarketing();
                proposalByCommericalAndMarketingParts.setDealername(dc.getDealerNameCN());
                proposalByCommericalAndMarketingParts.setSector(dc.getSector());
                proposalByCommericalAndMarketingParts.setLimitType("Part");
                proposalByCommericalAndMarketingParts.setInstanceId(instanceId);
                List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketingsParts = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(proposalByCommericalAndMarketingParts);
                if(StringUtils.isNotEmpty(proposalByCommericalAndMarketingsParts)){
                    if(StringUtils.isNotNull(proposalByCommericalAndMarketingsParts.get(0).getProposalLimit()) && !proposalByCommericalAndMarketingsParts.get(0).getProposalLimit().equals("") && !proposalByCommericalAndMarketingsParts.get(0).getProposalLimit().equals("0")) {
                        //说明包含Parts
                        isPart =true;
                    }
                }
            }
            hashMap.put("isPart",isPart);
            Map map1 = wordLabelController.generateWordHeader(hashMap);//pdf合并需要主表做标头，调用这个方法生成第一个pdf
            String amount = (String) map1.get("amount");
            String deposit = (String) map1.get("deposit");
            String expiredDate = (String) map1.get("expiredDate");
            //调用这个方法将同一分组合同拼在一个pdf里，保存在文件夹下，返回这个文件pdf的路径

            Map<String, Object> s = this.mergeWord(hashMap);
            DealercodeContractFiling dealercodeContractFilingTemp = new DealercodeContractFiling();
            dealercodeContractFilingTemp.setDealerNameCN(dc.getDealerNameCN());
            dealercodeContractFilingTemp.setSector(dc.getSector());
            dealercodeContractFilingTemp.setLimitType(dc.getLimitType());
            dealercodeContractFilingTemp.setInstanceId(instanceId);
            List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFilingTemp);
            if(StringUtils.isEmpty(dealercodeContractFilings)){
                DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
                dealercodeContractFiling.setContractLocation("/profile/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+s.get("contractName").toString()+".pdf");
                dealercodeContractFiling.setContractLocationHistory("/profile/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+s.get("contractName").toString()+".pdf");
                dealercodeContractFiling.setDealerNameCN(dc.getDealerNameCN());
                dealercodeContractFiling.setSector(dc.getSector());
                dealercodeContractFiling.setLimitType(dc.getLimitType());
                dealercodeContractFiling.setContractName(s.get("contractName").toString());
                dealercodeContractFiling.setInstanceId(instanceId);
                dealercodeContractFiling.setFacilityAmount(amount);
                dealercodeContractFiling.setDeposit(deposit);
                dealercodeContractFiling.setExpiredDate(expiredDate);
                dealercodeContractFiling.setContractNameHistory(s.get("contractNameHistory").toString());
                //给合同报表插值
                ContractRecord contractRecord = new ContractRecord();
                contractRecord.setInstanceid(instanceId);
                contractRecord.setDealername(dc.getDealerNameCN());
                contractRecord.setLimitType(dc.getLimitType());
                contractRecord.setSector(dc.getSector());
                List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList3(contractRecord);
                for (ContractRecord record : contractRecords) {
                    record.setFileUrl(dealercodeContractFiling.getContractLocation());
                    contractRecordMapper.updateContractRecord(record);
                }

                //
                if(isPart){
                    //给报表3插值
                    for (ContractRecord record : contractRecords) {
                        if(record.getSector().toUpperCase().equals("PEUGEOT") && record.getLimitType().toUpperCase().equals("NORMAL") && StringUtils.isNotEmpty(record.getPartsAmount()) && !record.getPartsAmount().equals("/")){
                            record.setFacilityamount(record.getPartsAmount());
                            record.setDeposit(record.getPartsDepositRatio());
                            record.setLimitType("Part");
                            record.setNote("Part合同");
                            contractRecordMapper.insertContractRecordThree(record);
                        }
                    }
                }
                //判断是否要出股东会议决
                if((dc.getPriority().equals("4") || dc.getPriority().equals("3"))){
                    //说明要出查询担保公司
                    //查该经销商下对应得担保人和担保机构
                    Securities securities = new Securities();
                    securities.setInstanceId(instanceId);
                    securities.setDealername(dc.getDealerNameCN());
                    List<Securities> securitiesList = securitiesMapper.selectSecuritiesList(securities);
                    StringBuilder stringS = new StringBuilder();
                    for(Securities se: securitiesList){
                        if(StringUtils.isNotEmpty(se.getGuaranteeType())){
                            if(se.getGuaranteeType().equals("corporate")){
                                if(!StringUtils.isEmpty(se.getProposalNameCN())){
                                    stringS.append(se.getProposalNameCN()).append(",");
                                }
                            }
                        }
                    }
                    if(StringUtils.isNotEmpty(stringS)) {
                        String Shareholders= (stringS.substring(0, stringS.length() - 1)).toString();//担保机构
                        String contractPath = wordLabelController.generateContract(Shareholders, dc.getDealerNameCN());
                        dealercodeContractFiling.setShareholdersPath(contractPath);
                        System.out.println("有股东会议");
                    }
                }

                dealercodeContractFilingMapper.insertDealercodeContractFiling(dealercodeContractFiling);
            }else{
                for (DealercodeContractFiling dealercodeContractFiling : dealercodeContractFilings) {
                    dealercodeContractFiling.setContractLocation("/profile/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+s.get("contractName").toString()+".pdf");
                    dealercodeContractFiling.setContractLocationHistory("/profile/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+s.get("contractName").toString()+".pdf");

                    if((dc.getPriority().equals("4") || dc.getPriority().equals("3"))){
                        //说明要出查询担保公司
                        //查该经销商下对应得担保人和担保机构
                        Securities securities = new Securities();
                        securities.setInstanceId(instanceId);
                        securities.setDealername(dc.getDealerNameCN());
                        List<Securities> securitiesList = securitiesMapper.selectSecuritiesList(securities);
                        StringBuilder stringS = new StringBuilder();
                        for(Securities se: securitiesList){
                            if(StringUtils.isNotEmpty(se.getGuaranteeType())){
                                if(se.getGuaranteeType().equals("corporate")){
                                    if(!StringUtils.isEmpty(se.getProposalNameCN())){
                                        stringS.append(se.getProposalNameCN()).append(",");
                                    }
                                }
                            }
                        }
                        if(StringUtils.isNotEmpty(stringS)) {
                            String Shareholders= (stringS.substring(0, stringS.length() - 1)).toString();//担保机构
                            String contractPath = wordLabelController.generateContract(Shareholders, dc.getDealerNameCN());
                            dealercodeContractFiling.setShareholdersPath(contractPath);
                            System.out.println("有股东会议");
                            System.out.println(contractPath);
                        }
                    }

                    dealercodeContractFilingMapper.updateDealercodeContractFiling(dealercodeContractFiling);
                    ContractRecord contractRecord = new ContractRecord();
                    contractRecord.setInstanceid(instanceId);
                    contractRecord.setDealername(dc.getDealerNameCN());
                    contractRecord.setLimitType(dealercodeContractFiling.getLimitType());
                    contractRecord.setSector(dc.getSector());
                    List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(contractRecord);
                    for (ContractRecord record : contractRecords) {
                        record.setFileUrl(dealercodeContractFiling.getContractLocation());
                        contractRecordMapper.updateContractRecord(record);
                    }
                }
            }
/*
            DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
            //dealercodeContractFiling.setContractLocation("/profile/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+s.get("contractName").toString()+".pdf");
            //dealercodeContractFiling.setContractLocationHistory("/profile/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+s.get("contractName").toString()+".pdf");
            dealercodeContractFiling.setDealerNameCN(dc.getDealerNameCN());
            dealercodeContractFiling.setSector(dc.getSector());
            dealercodeContractFiling.setLimitType(dc.getLimitType());
            dealercodeContractFiling.setContractName(s.get("contractName").toString());
            dealercodeContractFiling.setInstanceId(instanceId);
            dealercodeContractFiling.setFacilityAmount(amount);
            dealercodeContractFiling.setDeposit(deposit);
            dealercodeContractFiling.setExpiredDate(expiredDate);
            dealercodeContractFiling.setContractNameHistory(s.get("contractNameHistory").toString());
            //判断这个合同是否是二次生成，就看表里有没有，如果没有就新增，有的话，不管，数据库数据不需要变，变的是合同里的书签内容
            List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFiling);
            if(StringUtils.isEmpty(dealercodeContractFilings)){
                dealercodeContractFilingMapper.insertDealercodeContractFiling(dealercodeContractFiling);
                annualReviewyService.saveDbLog("1","新增归档合同信息",null,instanceId,null,dealercodeContractFiling,"CRO确认/合同刷新");
                //给合同报表插值
                ContractRecord contractRecord = new ContractRecord();
                contractRecord.setInstanceid(instanceId);
                contractRecord.setDealername(dc.getDealerNameCN());
                contractRecord.setLimitType(dc.getLimitType());
                contractRecord.setSector(dc.getSector());
                List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(contractRecord);
                for (ContractRecord record : contractRecords) {
                    record.setFileUrl(dealercodeContractFiling.getContractLocation());
                    contractRecordMapper.updateContractRecord(record);
                }
            }*/
            //然后删除该文件夹里的所有文件进行第二次分组的pdf合并
            FileUtils.delAllFile(RuoYiConfig.getProfile()+"/wordfill/word/"+instanceId);
            FileUtils.delAllFile(RuoYiConfig.getProfile()+"/wordfill/pdf/"+instanceId);
        }
    }

    @PostMapping("/toWord")
    public void generateWord(@RequestBody Map parameters) {
        try {
//            String parameters="af359e97cb424cd0a0c3409ae61c2baf";
//            String[] params = parameters.split(",");
//            String[] params = {"af359e97cb424cd0a0c3409ae61c2baf"};
//            String contractId = "fe7da17113264ecfa640dd69b699667d";
            System.out.println("合同下载成功");
            String contractlocation =(String)parameters.get("contractlocation");
            String contractname =(String)parameters.get("contractname");

//            String dealerNameCN =(String)parameters.get("dealerNameCN");
//            String sector =(String)parameters.get("sector");
//            String instanceId =(String)parameters.get("instanceId");
            String contract =(String)parameters.get("contract");
            //调用方法通过传的参数获取到该合同的dealercode
//            String dealercode = dealercodelist(instanceId, dealerNameCN, sector);

            Map<String, Object> data = new HashMap<>();


            data.put("contract",contract);
            data.put("groupGuarantee","测试");
            data.put("name",contractname);
//            String path = this.getClass().getClassLoader().getResource("").getPath();
            String a = RuoYiConfig.getProfile() + contractlocation.substring(8);
            XWPFTemplate template = XWPFTemplate.compile("/"+RuoYiConfig.getProfile() + contractlocation.substring(8))
                    .render(data);
            OutputStream out;
//            response.reset();
//            response.addHeader("Access-Control-Allow-Origin", "*");
//            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
//            response.setContentType("application/force-download");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(String.valueOf(contractname)+".docx","utf-8"));
//            response.setHeader("Access-Control-Expose-Headers", "FileName");
//            out= response.getOutputStream();
             out = new FileOutputStream("/"+RuoYiConfig.getProfile()+"/wordfill/word/"+contractname+".docx");
            template.write(out);
            out.flush();
            out.close();
            template.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @PostMapping("/daxue")
    public String daxue(@RequestBody Map parameters) {
//        String daxue =(String)parameters.get("daxue");
//        String daxue1 =(String)parameters.get("daxue1");
//        String numberStr = Convert.toStr(Convert.toInt(Arith.mul(Convert.toDouble(daxue),Convert.toDouble(daxue1))));
//        return numberStr;
        CreditCondition cc = new CreditCondition();
        cc.setDealername("保利汽车（深圳）有限公司");
        cc.setSector("MASERATI");
        cc.setLimittype("NORMAL");
        cc.setInstanceid("AR2022100811");
        CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
        WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
        wpc.setDealername("保利汽车（深圳）有限公司");
        wpc.setSector("MASERATI");
        wpc.setLimitType("NORMAL");
        wpc.setInstanceId("AR2022100811");
        WholesalePerformanceCurrently wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc).get(0);
        //判断CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就走这个合同
        String dateToStr = null;
        if(StringUtils.isNotNull(creditCondition.getExpireddate())){
            dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", creditCondition.getExpireddate());
        }else {
            dateToStr="";
        }
        if (!dateToStr.equals(wholesalePerformanceCurrently.getExpiryDate())) {
            System.out.println("aaaa");
        }
return "aa";
    }
    @PostMapping("/toWorddd")
    public void generateWor(@RequestBody Map parameters) {

        try {
            String contractlocation =(String)parameters.get("contractlocation");
            String contractname =(String)parameters.get("contractname");
            String instanceid =(String)parameters.get("instanceid");
            String contract =(String)parameters.get("contract");
            //加载包含书签的Word文档
            Document doc = new Document();
            doc.loadFromFile(RuoYiConfig.getProfile() + contractlocation.substring(8));


            //定位到指定书签位置
            BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);

            //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
//            bookmarksNavigator.moveToBookmark("保证人表格一");
//            bookmarksNavigator.replaceBookmarkContent(" ",true);
//            bookmarksNavigator.moveToBookmark("保证人表格二");
//            bookmarksNavigator.replaceBookmarkContent(" ",true);

            String a ="法分开结案浩丰科技安徽发空间发";
            StringBuilder stringBuilder = new StringBuilder();
            if(a.length()<25){
                int b = 25 - a.length();
                for (int i = 0; i < b/2; i++) {
                    stringBuilder.append("\t");
                }
                a = a+stringBuilder;
            }
            bookmarksNavigator.moveToBookmark("经销商法人");
            bookmarksNavigator.replaceBookmarkContent(a,true);

            bookmarksNavigator.moveToBookmark("经销商法人A1");
            bookmarksNavigator.replaceBookmarkContent(a,true);

            bookmarksNavigator.moveToBookmark("经销商法人A2");
            bookmarksNavigator.replaceBookmarkContent(a,true);

            bookmarksNavigator.moveToBookmark("经销商法人A3");
            bookmarksNavigator.replaceBookmarkContent(a,true);

//            bookmarksNavigator.moveToBookmark("保证人表格一");
//            bookmarksNavigator.replaceBookmarkContent("保证人表格一",true);
//            bookmarksNavigator.moveToBookmark("保证人表格二");
//            bookmarksNavigator.replaceBookmarkContent("保证人表格一",true);
//            bookmarksNavigator.moveToBookmark("保证人表格三");
//            bookmarksNavigator.replaceBookmarkContent(" ",true);

//
//            bookmarksNavigator.moveToBookmark("签署合同日期2");
//            bookmarksNavigator.replaceBookmarkContent("2022年10月11日",true);
//
//            bookmarksNavigator.moveToBookmark("人民币循环贷款主合同号");
//            bookmarksNavigator.replaceBookmarkContent("M75502F22OCT086",true);


//            //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
//            bookmarksNavigator.replaceBookmarkContent("9",true);
//            bookmarksNavigator.moveToBookmark("id");
//
//            //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
//            bookmarksNavigator.replaceBookmarkContent("详细信息",true);
//
//            bookmarksNavigator.moveToBookmark("feike");
//
//            //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
//            bookmarksNavigator.replaceBookmarkContent("菲克",true);

            File file2 = new File(RuoYiConfig.getProfile()+"/wordfill/word/"+instanceid);
            if (file2.mkdir()) {
                System.out.println("单文件夹"+instanceid+"创建成功！创建后的文件目录为：" + file2.getPath() + ",上级文件为:" + file2.getParent());
            }
            //保存文档FileFormat.Docx_2013
            doc.saveToFile("/"+RuoYiConfig.getProfile()+"/wordfill/word/"+instanceid+"/"+contractname+".docx",FileFormat.Docx_2013);
            doc.dispose();

            //重新读取生成的文档
            InputStream is = new FileInputStream("/"+RuoYiConfig.getProfile()+"/wordfill/word/"+instanceid+"/"+contractname+".docx");
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os=new FileOutputStream("/"+RuoYiConfig.getProfile()+"/wordfill/word/"+instanceid+"/"+contractname+".docx");
            document.write(os);
            os.flush();
            os.close();
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/toWords")
        public  void toWords() throws IOException {
            //1.在java中创建一个保存数据的map，key为对应word文本中的标签，值为要替换的数据，会将map中的对应的key替换为value
            Map<String, Object> datas = new HashMap<String, Object>();
            //2.给map添加要替换的数据
            //(1)简单的数据，替换的文本数据
            datas.put("groupGuarantee", "数据内容");//可直接添加到map中
            //(2)动态的表格列表数据，要创建List集合，数据类型为map类型，map中的key为word中要遍历的列，值为要替换的内容
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();//创建map的List集合
            for (int i = 0; i < 6; i++) {    //用循环添加每行的数据，添加6行数据
                Map<String, Object> detailMap = new HashMap<String, Object>();//将word中标签名的例和对应数据保存到map
                detailMap.put("index", i + 1);//序号
                detailMap.put("title", "商品" + i);//商品名称
                detailMap.put("product_description", "套");//商品规格
                detailMap.put("buy_num", 3 + i);//销售数量
                detailMap.put("saleprice", 100 + i);//销售价格
                list.add(detailMap);//将设置好的行保存到list集合中
            }
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();//创建一个列表的规则
            Configure config = Configure.newBuilder().bind("list", policy).build();//设置列表配置，如果有多个列表时需加.bind("list1", policy) 新列表配置即可
//            datas.put("list", list);        //将列表保存到渲染的map中
            //3.创建XWPFTemplate对象，并设置读取模板路径和要渲染的数据
            XWPFTemplate template = XWPFTemplate.compile(this.getClass().getClassLoader().getResource("").getPath() + "/template/二手车业务-最高额保证担保合同（清洁稿）.docx", config).render(datas);
            //compile(模板路径,对应的配置)方法是设置模板路径和模板配置的，如果不设置配置时可不传config
            //render(datas)方法是用来渲染数据，将准备好的map数据方进去渲染
            //4.模板的输出，用FileOutputStream输出流（可以输出到指定文件位置，也可以用ajax直接返回给浏览器下载）
            FileOutputStream out = new FileOutputStream("D:/out/1.docx");//创建文件输出流并指定位置
            template.write(out);    //用XWPFTemplate对象的写write()方法将流写入
        }

//    public void generateWords(@RequestBody Map parameters, HttpServletResponse response) {
//        try {
////            String parameters="af359e97cb424cd0a0c3409ae61c2baf";
////            String[] params = parameters.split(",");
//            List params = (List) parameters.get("params");
//            String contractId = String.valueOf(parameters.get("contractId"));
////            String[] params = {"af359e97cb424cd0a0c3409ae61c2baf"};
////            String contractId = "fe7da17113264ecfa640dd69b699667d";
//            for (int i = 0; i < params.size(); i++) {
//                params.set(i,"'"+params.get(i)+"'");
//            }
//            Object[] arr = params.toArray();
//            Map<String, Object> data = new HashMap<>();
//            Map map = fileWorkService.getDataById(contractId,"iyzlv_contract");
//            List<Map> sqlTexts = fileWorkService.getDataByParentId(contractId,"iyzlv_sqltext");
//            Map templateObj = fileWorkService.getDataById(map.get("templateId").toString(),"contract_template");
//            for (Map sqlText : sqlTexts) {
//                String sqlString = String.valueOf(sqlText.get("sqlString"));
//                String sql = MessageFormat.format(sqlString, arr);
//                Map mapSon = fileWorkService.getData(sql);
//                data.putAll(mapSon);
//            }
//            XWPFTemplate template = XWPFTemplate.compile(this.getClass().getClassLoader().getResource("").getPath() + templateObj.get("address").toString())
//                    .render(data);
//            OutputStream out;
//            response.reset();
//            response.addHeader("Access-Control-Allow-Origin", "*");
//            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
//            response.setContentType("application/force-download");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(String.valueOf(map.get("contractName"))+".docx","utf-8"));
//            response.setHeader("Access-Control-Expose-Headers", "FileName");
//            out= response.getOutputStream();
////             out = new FileOutputStream("D:\\下载\\二手车业务-最高额保证担保合同.docx");
//            template.write(out);
//            out.flush();
//            out.close();
//            template.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }

    /**
     * 生成001的编号
     *
     * @param maxNum 最大数
     * @param count  累计的
     * @return
     */
    public static String sequenceCode(Long maxNum, Long count) {
        String strNum = String.valueOf(maxNum + count);
        if (StringUtils.isEmpty(strNum) || 1 >= strNum.length()) {
            return "";
        }
        return strNum.substring(1);
    }

    /**
     * 获取流程下对应得dealercode
     */
    public String dealercodelist(String instanceId,String dealerNameCN,String sector) {
        BasicInformation basicInformation = new BasicInformation();
        basicInformation.setInstanceId(instanceId);
        basicInformation.setDealerNameCN(dealerNameCN);
        List<BasicInformation> basicInformations = basicInformationService.selectBasicInformationList(basicInformation);
        if(StringUtils.isEmpty(basicInformations)){
            throw new BaseException("BasicInformation没对应得数据");
        }
        BasicInformation basicInformation1 = basicInformations.get(0);
        String sector1 = basicInformation1.getSector();
        String dealerCodeFromWFS = basicInformation1.getDealerCodeFromWFS();
        String[] split = sector1.split(",");
        String[] splits = dealerCodeFromWFS.split(",");
        String dealercode = "";
        for (int i = 0; i <split.length ; i++) {
            if(split[i].equals(sector)){
                for (int j = 0; j <splits.length ; j++) {
                    dealercode = splits[i];
                }
            }
        }
        return dealercode;
    }

    /**
     * 拼主合同号
     */
    public String maincontractno (String dealercode,String letter) {
        DealercodeCount dealercodeCount = new DealercodeCount();
        dealercodeCount.setDealercode(dealercode);
        dealercodeCount.setTemp(letter);
        List<DealercodeCount> dealercodeCounts = dealercodeCountService.selectDealercodeCountList(dealercodeCount);
        if(StringUtils.isEmpty(dealercodeCounts)){
            dealercodeCount.setTemp(letter);
            dealercodeCount.setCount((long) 1);
            dealercodeCountService.insertDealercodeCount(dealercodeCount);
        }

        //拼人民币循环贷款主合同号
        String year = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
        String month = new SimpleDateFormat("M", Locale.CHINESE).format(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String dateNowStr = sdf.format(new Date());
        try {
            month = new SimpleDateFormat("MMMMM", Locale.US).format((new SimpleDateFormat("MM")).parse(month));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        DealercodeCount dealercodeCount1 = dealercodeCountService.selectDealercodeCountList(dealercodeCount).get(0);
        Long count = dealercodeCount1.getCount();
        String code = sequenceCode((long) 1000, count);
        //用完这个字段开始自增，并且自增后的值如果超过999就从1重新开始,或者当日期为一月一日时也从1开始计算
//        BeanUtil.copyProperties(dealercodeCount1,dealercodeCount);
//        if(count+1>999 || dateNowStr.equals("01-01")){
//            dealercodeCount.setCount((long)1);
//        }else {
//
//            dealercodeCount.setCount(count+1);
//        }
//        dealercodeCountService.updateDealercodeCount(dealercodeCount);
        //TODO 用变量
        String contrctcode = dealercode+letter+year+month+code;
        return contrctcode;
    }

    @PostMapping("/updatedealercodeCount")
    //合同下载页面走过后，修改dealercodeCount的count值，编号值在每次结束流程结束的时候自增
    public int updatedealercodeCount(){
        DealercodeCount dealercodeCount = new DealercodeCount();
        //查该表全部数据，然后把count编号全加一遍
        List<DealercodeCount> dealercodeCounts = dealercodeCountService.selectDealercodeCountList(dealercodeCount);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String dateNowStr = sdf.format(new Date());
        for (DealercodeCount dc : dealercodeCounts){
            //自增后的值如果超过999就从1重新开始,或者当日期为一月一日时也从1开始计算
            if(dc.getCount()+1>999 || dateNowStr.equals("01-01")){
                dc.setCount((long)1);
            }else {

                dc.setCount(dc.getCount()+1);
            }
            dealercodeCountService.updateDealercodeCount(dc);
        }
        return 1;
    }

    public static void main(String[] args) {
//        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("a").append(",").append("b").append(",");
//        String danbaorenOrDanbaojigou = (stringBuilder.substring(0, stringBuilder.length() - 1)).toString();
//        String[] split = danbaorenOrDanbaojigou.split(",");
//        for (int i = 0; i < split.length; i++) {
//            System.out.println(split[i]);
//        }
//        long c = 11111;
//        String b = "5%";
//        double a =15;
//        double mul = Arith.mul(16000000, 20 * 0.01);
//        Long a4 = (long)(mul*1000);
//        Long a3 = (long)mul*1000;
//        System.out.println(a4);
//        System.out.println(a3);
//        System.out.println(mul);
//        System.out.println(Convert.toStr(Convert.getDoubleString(111111.111)));
//
        String currentYear = DateUtils.getCurrentYear();
        String substring = currentYear.substring(2);
        String a1 = "";
        String a2 = "";

        a2 ="2022-12-23";
//        if(a1.equals(a2)){
//            System.out.println("dad");
//        }

//        char[] a = c.toCharArray();
//        StringBuilder stringBuilder = new StringBuilder(c);
//        StringBuilder m = stringBuilder.replace(6, 7, "M");
//        System.out.println(m.toString());
//        char c1 = c.charAt(6);
//        System.out.println(c1);
//        String o = "[{\"VinNo\":\"1C4HJXEN8MW846733\",\"VinOption\":[{\"loanOSAmount\":\"445000\",\"vin\":\"1C4HJXEN8MW846733\"},{\"loanOSAmount\":\"445000\",\"vin\":\"1C4HJXEN1MW846704\"},{\"loanOSAmount\":\"449950\",\"vin\":\"1C4HJXEN7MW825596\"},{\"loanOSAmount\":\"449950\",\"vin\":\"1C4HJXEN4MW841853\"},{\"loanOSAmount\":\"361312.7\",\"vin\":\"1C4JJXR66MW848761\"},{\"loanOSAmount\":\"485000\",\"vin\":\"1C4HJXENXNW130739\"},{\"loanOSAmount\":\"514300\",\"vin\":\"1C4HJXFN5NW131389\"}],\"id\":1,\"originalBalance\":\"445000\"}]";
//////        List<Map<String, Object>> vehicle1 = (List<Map<String, Object>>)o;
////        List<Map<String, Object>> collections = JSON.parseObject(o, List.class);
//////        List<Map<String, Object>> stringList = objToList(o);
////        for (Map<String, Object> a:collections){
////            System.out.println(a.get("VinNo"));
////        }
        Map<String, Object> map = new HashMap<>();
        map.put("dd",a1);
        String dd = (String) map.get("dd");
        DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
        dealercodeContractFiling.setExpiredDate(dd);
        boolean cc =false;
        if(StringUtils.isEmpty(a1) || a1.equals(a2)){
            cc=true;
        }
        String xx="D51204CB20OCT941";
        String num = "108,528,133,266.13";
        String replace = num.replace(",", "");
        System.out.println(xx.length());
        System.out.println(dealercodeContractFiling.getExpiredDate());
        System.out.println(DateUtils.getCurrentMonth());
        System.out.println(DateUtils.getCurrentYear());
    }
    static List<Map<String, Object>> objToList(Object obj) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                System.out.println(o);
                result.add(Map.class.cast(o));
            }
        }
        return result;
    }

    @RequestMapping("/export")
    public void generateWords(@RequestBody Map parameters, HttpServletRequest request , HttpServletResponse response) {
//        ExcelExportUtil.abc(request,response);
    }
}
